<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { ElMessage, ElMessageBox, ElLoading } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import {
  getUsers,
  addUser,
  updateUser,
  deleteUser,
  updateUserStatus,
  getRoles,
  getStatuses,
  type User,
} from '@/services/userService'

// 页面动画效果
const pageClass = ref('')

// 用户列表
const users = ref<User[]>([])

// 搜索条件
const searchForm = reactive({
  keyword: '',
  role: '',
  status: '',
})

// 过滤后的用户列表
const filteredUsers = ref<User[]>([])

// 加载状态
const loading = ref(false)

// 角色和状态选项
const roleOptions = getRoles()
const statusOptions = getStatuses()

// 对话框相关
const dialogVisible = ref(false)
const dialogTitle = ref('新增用户')
const formRef = ref<FormInstance>()
const userForm = reactive({
  id: 0,
  username: '',
  name: '',
  password: '',
  confirmPassword: '',
  role: 'user',
  department: '',
  email: '',
  phone: '',
  status: 'active',
})

// 表单验证规则
const formRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' },
  ],
  name: [{ required: true, message: '请输入姓名', trigger: 'blur' }],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur', validator: validatePassword },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur', validator: validateConfirmPassword },
  ],
  role: [{ required: true, message: '请选择角色', trigger: 'change' }],
  department: [{ required: true, message: '请输入部门', trigger: 'blur' }],
  email: [{ type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }],
  phone: [{ pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号码', trigger: 'blur' }],
})

// 密码验证
function validatePassword(rule: any, value: string, callback: any) {
  if (dialogTitle.value === '编辑用户' && !value) {
    // 编辑模式下密码可以为空（不修改密码）
    callback()
  } else if (!value) {
    callback(new Error('请输入密码'))
  } else if (value.length < 6) {
    callback(new Error('密码长度不能小于6位'))
  } else {
    if (userForm.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

// 确认密码验证
function validateConfirmPassword(rule: any, value: string, callback: any) {
  if (dialogTitle.value === '编辑用户' && !value && !userForm.password) {
    // 编辑模式下密码可以为空（不修改密码）
    callback()
  } else if (!value) {
    callback(new Error('请再次输入密码'))
  } else if (value !== userForm.password) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

/**
 * 加载用户列表
 */
async function loadUsers() {
  loading.value = true
  try {
    users.value = await getUsers()
    searchUsers()
  } catch (error) {
    console.error('加载用户列表失败:', error)
    ElMessage.error('加载用户列表失败')
  } finally {
    loading.value = false
  }
}

/**
 * 搜索用户
 */
function searchUsers() {
  filteredUsers.value = users.value.filter((user) => {
    // 关键词搜索（用户名、姓名、部门、邮箱、手机）
    const keywordMatch =
      !searchForm.keyword ||
      user.username.toLowerCase().includes(searchForm.keyword.toLowerCase()) ||
      user.name.toLowerCase().includes(searchForm.keyword.toLowerCase()) ||
      user.department.toLowerCase().includes(searchForm.keyword.toLowerCase()) ||
      user.email.toLowerCase().includes(searchForm.keyword.toLowerCase()) ||
      user.phone.includes(searchForm.keyword)

    // 角色筛选
    const roleMatch = !searchForm.role || user.role === searchForm.role

    // 状态筛选
    const statusMatch = !searchForm.status || user.status === searchForm.status

    return keywordMatch && roleMatch && statusMatch
  })
}

/**
 * 重置搜索条件
 */
function resetSearch() {
  searchForm.keyword = ''
  searchForm.role = ''
  searchForm.status = ''
  filteredUsers.value = [...users.value]
}

/**
 * 打开新增用户对话框
 */
function openAddDialog() {
  dialogTitle.value = '新增用户'
  resetForm()
  dialogVisible.value = true
}

/**
 * 打开编辑用户对话框
 * @param user 要编辑的用户
 */
function openEditDialog(user: any) {
  dialogTitle.value = '编辑用户'
  resetForm()

  // 填充表单数据
  userForm.id = user.id
  userForm.username = user.username
  userForm.name = user.name
  userForm.role = user.role
  userForm.department = user.department
  userForm.email = user.email
  userForm.phone = user.phone
  userForm.status = user.status

  // 清空密码字段（编辑时不显示密码）
  userForm.password = ''
  userForm.confirmPassword = ''

  dialogVisible.value = true
}

/**
 * 重置表单
 */
function resetForm() {
  userForm.id = 0
  userForm.username = ''
  userForm.name = ''
  userForm.password = ''
  userForm.confirmPassword = ''
  userForm.role = 'user'
  userForm.department = ''
  userForm.email = ''
  userForm.phone = ''
  userForm.status = 'active'

  // 重置表单验证
  formRef.value?.resetFields()
}

/**
 * 提交表单
 */
async function submitForm() {
  if (!formRef.value) return

  await formRef.value.validate(async (valid) => {
    if (valid) {
      const loadingInstance = ElLoading.service({ fullscreen: true, text: '保存中...' })

      try {
        if (userForm.id === 0) {
          // 新增用户
          await addUser({
            username: userForm.username,
            name: userForm.name,
            password: userForm.password,
            role: userForm.role,
            department: userForm.department,
            email: userForm.email,
            phone: userForm.phone,
            status: userForm.status as 'active' | 'inactive',
          })

          ElMessage.success('用户添加成功')
        } else {
          // 编辑用户
          const updateData: any = {
            id: userForm.id,
            name: userForm.name,
            role: userForm.role,
            department: userForm.department,
            email: userForm.email,
            phone: userForm.phone,
            status: userForm.status,
          }

          // 如果密码不为空，则更新密码
          if (userForm.password) {
            updateData.password = userForm.password
          }

          await updateUser(updateData)
          ElMessage.success('用户更新成功')
        }

        // 重新加载用户列表
        await loadUsers()

        // 关闭对话框
        dialogVisible.value = false
      } catch (error: any) {
        console.error('保存用户失败:', error)
        ElMessage.error(error.message || '操作失败，请重试')
      } finally {
        loadingInstance.close()
      }
    } else {
      return false
    }
  })
}

/**
 * 确认删除用户
 * @param user 要删除的用户
 */
function confirmDelete(user: any) {
  ElMessageBox.confirm(`确定要删除用户 "${user.name}" 吗？`, '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      deleteUser(user)
    })
    .catch(() => {
      // 用户取消删除
    })
}

/**
 * 删除用户
 * @param user 要删除的用户
 */
async function deleteUser(user: User) {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '删除中...' })

  try {
    // 调用删除API
    const success = await deleteUser(user.id)

    if (success) {
      // 重新加载用户列表
      await loadUsers()
      ElMessage.success('用户删除成功')
    } else {
      ElMessage.error('删除失败，用户不存在')
    }
  } catch (error) {
    console.error('删除用户失败:', error)
    ElMessage.error('删除失败，请重试')
  } finally {
    loadingInstance.close()
  }
}

/**
 * 更新用户状态
 * @param user 用户
 * @param status 新状态
 */
async function changeUserStatus(user: User, status: 'active' | 'inactive') {
  const loadingInstance = ElLoading.service({ fullscreen: true, text: '更新中...' })

  try {
    // 调用更新状态API
    await updateUserStatus(user.id, status)

    // 重新加载用户列表
    await loadUsers()

    ElMessage.success(`用户已${status === 'active' ? '启用' : '禁用'}`)
  } catch (error) {
    console.error('更新用户状态失败:', error)
    ElMessage.error('操作失败，请重试')
  } finally {
    loadingInstance.close()
  }
}

/**
 * 获取角色标签类型
 * @param role 角色
 * @returns 标签类型
 */
function getRoleTagType(role: string): '' | 'success' | 'warning' | 'danger' {
  switch (role) {
    case 'admin':
      return 'danger'
    case 'manager':
      return 'warning'
    case 'user':
      return 'success'
    default:
      return ''
  }
}

/**
 * 获取角色显示名称
 * @param role 角色
 * @returns 角色显示名称
 */
function getRoleName(role: string): string {
  switch (role) {
    case 'admin':
      return '系统管理员'
    case 'manager':
      return '管理人员'
    case 'user':
      return '普通用户'
    default:
      return role
  }
}

/**
 * 获取状态标签类型
 * @param status 状态
 * @returns 标签类型
 */
function getStatusTagType(status: string): '' | 'success' | 'info' | 'warning' | 'danger' {
  switch (status) {
    case 'active':
      return 'success'
    case 'inactive':
      return 'info'
    default:
      return ''
  }
}

/**
 * 获取状态显示名称
 * @param status 状态
 * @returns 状态显示名称
 */
function getStatusName(status: string): string {
  switch (status) {
    case 'active':
      return '正常'
    case 'inactive':
      return '禁用'
    default:
      return status
  }
}

/**
 * 组件挂载时的动画效果和数据加载
 */
onMounted(async () => {
  // 加载用户列表
  await loadUsers()

  // 添加进入动画类
  setTimeout(() => {
    pageClass.value = 'page-show'
  }, 100)
})
</script>

<template>
  <div class="user-management" :class="pageClass">
    <div class="page-header">
      <h1>用户管理</h1>
      <div class="header-actions">
        <el-button type="primary" @click="openAddDialog">
          <el-icon><Plus /></el-icon> 新增用户
        </el-button>
      </div>
    </div>

    <div class="page-content">
      <!-- 搜索区域 -->
      <el-card class="search-card">
        <el-form :model="searchForm" inline>
          <el-form-item label="关键词">
            <el-input
              v-model="searchForm.keyword"
              placeholder="用户名/姓名/部门/邮箱/手机"
              clearable
              @keyup.enter="searchUsers"
            />
          </el-form-item>
          <el-form-item label="角色">
            <el-select v-model="searchForm.role" placeholder="全部" clearable>
              <el-option
                v-for="option in roleOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="全部" clearable>
              <el-option
                v-for="option in statusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchUsers">
              <el-icon><Search /></el-icon> 搜索
            </el-button>
            <el-button @click="resetSearch">
              <el-icon><RefreshRight /></el-icon> 重置
            </el-button>
          </el-form-item>
        </el-form>
      </el-card>

      <!-- 用户列表 -->
      <el-card class="table-card">
        <template #header>
          <div class="card-header">
            <span>用户列表</span>
            <span class="user-count">共 {{ filteredUsers.length }} 个用户</span>
          </div>
        </template>

        <el-table
          :data="filteredUsers"
          style="width: 100%"
          border
          stripe
          v-loading="loading"
          element-loading-text="加载中..."
        >
          <el-table-column prop="username" label="用户名" min-width="100" />
          <el-table-column prop="name" label="姓名" min-width="100" />
          <el-table-column prop="role" label="角色" width="120">
            <template #default="scope">
              <el-tag :type="getRoleTagType(scope.row.role)">
                {{ getRoleName(scope.row.role) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="department" label="部门" min-width="150" show-overflow-tooltip />
          <el-table-column prop="email" label="邮箱" min-width="180" show-overflow-tooltip />
          <el-table-column prop="phone" label="手机" min-width="120" />
          <el-table-column
            prop="lastLogin"
            label="最后登录"
            min-width="150"
            show-overflow-tooltip
          />
          <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
              <el-tag :type="getStatusTagType(scope.row.status)">
                {{ getStatusName(scope.row.status) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120" fixed="right">
            <template #default="scope">
              <el-dropdown trigger="click">
                <el-button size="small" type="primary" plain>
                  操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
                </el-button>
                <template #dropdown>
                  <el-dropdown-menu>
                    <el-dropdown-item @click="openEditDialog(scope.row)">
                      <el-icon><Edit /></el-icon> 编辑
                    </el-dropdown-item>
                    <el-dropdown-item
                      v-if="scope.row.status === 'active'"
                      @click="changeUserStatus(scope.row, 'inactive')"
                    >
                      <el-icon><Lock /></el-icon> 禁用
                    </el-dropdown-item>
                    <el-dropdown-item v-else @click="changeUserStatus(scope.row, 'active')">
                      <el-icon><Unlock /></el-icon> 启用
                    </el-dropdown-item>
                    <el-dropdown-item
                      divided
                      @click="confirmDelete(scope.row)"
                      style="color: #f56c6c"
                    >
                      <el-icon><Delete /></el-icon> 删除
                    </el-dropdown-item>
                  </el-dropdown-menu>
                </template>
              </el-dropdown>
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </div>

    <!-- 新增/编辑用户对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="formRef"
        :model="userForm"
        :rules="formRules"
        label-width="100px"
        label-position="right"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="userForm.username" :disabled="dialogTitle === '编辑用户'" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="userForm.name" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="userForm.password" type="password" show-password />
          <div class="form-tip" v-if="dialogTitle === '编辑用户'">留空表示不修改密码</div>
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="userForm.confirmPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="角色" prop="role">
          <el-select v-model="userForm.role" style="width: 100%">
            <el-option
              v-for="option in roleOptions"
              :key="option.value"
              :label="option.label"
              :value="option.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-input v-model="userForm.department" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="userForm.email" />
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="userForm.phone" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="userForm.status">
            <el-radio v-for="option in statusOptions" :key="option.value" :label="option.value">
              {{ option.label }}
            </el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<style lang="scss" scoped>
.user-management {
  background: linear-gradient(135deg, #ffecb3 0%, #ffcc80 100%);
  opacity: 0;
  transform: translateY(20px);
  transition: all 0.5s ease;
  height: 100%;
  padding: 16px;

  &.page-show {
    opacity: 1;
    transform: translateY(0);
  }
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h1 {
    color: #b71c1c;
    margin: 0;
    text-shadow: 1px 1px 2px rgba(0, 0, 0, 0.1);
  }

  .header-actions {
    display: flex;
    gap: 8px;
  }
}

.page-content {
  display: flex;
  flex-direction: column;
  gap: 16px;

  .search-card {
    background: rgba(255, 248, 225, 0.9);
    border-color: #ffcc80;

    :deep(.el-card__body) {
      padding: 15px;
    }
  }

  .table-card {
    background: rgba(255, 248, 225, 0.9);
    border-color: #ffcc80;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .user-count {
        font-size: 14px;
        color: #7f4f24;
      }
    }

    :deep(.el-table) {
      background-color: transparent;

      .el-table__header th {
        background-color: #ffb74d;
        color: #7f4f24;
        font-weight: bold;
      }

      .el-table__row {
        background-color: rgba(255, 255, 255, 0.7);

        &:hover > td {
          background-color: rgba(255, 224, 178, 0.7) !important;
        }
      }

      .el-table__row--striped td {
        background-color: rgba(255, 243, 224, 0.7);
      }
    }
  }
}

:deep(.el-button--primary) {
  background-color: #e65100;
  border-color: #e65100;

  &:hover,
  &:focus {
    background-color: #f57c00;
    border-color: #f57c00;
  }

  &.is-plain {
    color: #e65100;
    background-color: #fff3e0;
    border-color: #ffcc80;

    &:hover,
    &:focus {
      background-color: #ffe0b2;
      border-color: #e65100;
    }
  }
}

:deep(.el-input__inner),
:deep(.el-textarea__inner) {
  border-color: #ffcc80;

  &:focus {
    border-color: #e65100;
  }
}

:deep(.el-select .el-input.is-focus .el-input__inner) {
  border-color: #e65100;
}

:deep(.el-radio__input.is-checked .el-radio__inner) {
  background-color: #e65100;
  border-color: #e65100;
}

:deep(.el-radio__input.is-checked + .el-radio__label) {
  color: #e65100;
}

:deep(.el-dialog) {
  background: linear-gradient(135deg, #fff8e1 0%, #fff3e0 100%);
  border: 1px solid #ffcc80;
  border-radius: 8px;

  .el-dialog__header {
    background: linear-gradient(to right, #ffb74d, #ff9800);
    color: #7f4f24;
    border-radius: 8px 8px 0 0;
    padding: 15px 20px;

    .el-dialog__title {
      color: #7f4f24;
      font-weight: bold;
    }
  }

  .el-dialog__body {
    color: #5d4037;
  }

  .el-form-item__label {
    color: #7f4f24;
  }
}

:deep(.el-dropdown-menu) {
  background-color: #fff8e1;
  border: 1px solid #ffcc80;

  .el-dropdown-menu__item {
    color: #7f4f24;

    &:hover {
      background-color: #ffe0b2;
      color: #e65100;
    }

    .el-icon {
      margin-right: 5px;
      color: #e65100;
    }
  }
}

.form-tip {
  font-size: 12px;
  color: #7f4f24;
  margin-top: 4px;
}
</style>
